/**
 * @file 封装日志
 */
import Taro from "@tarojs/taro";
import VERSION from "@/config";
import { formatTime } from "./";

// 判断是否微信环境以及微信基础库版本
const canIUseLogManage = Taro.getEnv() === Taro.ENV_TYPE.WEAPP && Taro.canIUse("getLogManager");
const logger = canIUseLogManage ? Taro.getLogManager({ level: 0 }) : null;
const realtimeLogger = Taro.getRealtimeLogManager ? Taro.getRealtimeLogManager() : null;

/**
 * 日志只打印到本地，不上传到服务器
 * @param {string} file 所在文件名
 * @param args
 * @param  {...any} arg 参数
 */

export function DEBUG(file: string, ...args) {
  console.debug(file, " | ", ...args);
  if (canIUseLogManage) {
    logger?.debug(`[${VERSION}]`, file, " | ", ...args);
  }
  realtimeLogger && realtimeLogger.info(`[${VERSION}]`, file, " | ", ...args);
}

/**
 *
 * @param {string} file 所在文件名
 * @param args
 * @param  {...any} arg 参数
 */
export function RUN(file: string, ...args) {
  console.log(file, " | ", ...args);
  if (canIUseLogManage) {
    logger?.log(`[${VERSION}]`, file, " | ", ...args);
  }
  realtimeLogger && realtimeLogger.info(`[${VERSION}]`, file, " | ", ...args);

  // 记录到本地，用来logs页面展示
  // 展示本地存储能力
  const logs: string[] = Taro.getStorageSync("logs") || [];
  logs.unshift(`${formatTime(new Date())} ${file} | ${args[0]}`);
  Taro.setStorageSync("logs", logs);
}

/**
 *
 * @param {string} file 所在文件名
 * @param args
 * @param  {...any} arg 参数
 */
export function ERROR(file: string, ...args: any[]) {
  console.error(file, " | ", ...args);
  if (canIUseLogManage) {
    logger?.warn(`[${VERSION}]`, file, " | ", ...args);
  }
  if (realtimeLogger) {
    realtimeLogger.error(`[${VERSION}]`, file, " | ", ...args);
    // 判断是否支持设置模糊搜索
    if (realtimeLogger.setFilterMsg) {
      try {
        realtimeLogger.setFilterMsg(
          `[${VERSION}] ${file} ${JSON.stringify(args)}`
        );
      } catch (e) {
        realtimeLogger.setFilterMsg(`[${VERSION}] ${file}`);
      }
    }
  }
}

export function getLogger(fileName: string): {
  DEBUG: (...args: any) => void,
  RUN: (...args: any) => void,
  ERROR: (...args: any) => void
} {
  return {
    DEBUG: function (...args: any) {
      DEBUG(fileName, ...args);
    },
    RUN: function (...args: any) {
      RUN(fileName, ...args);
    },
    ERROR: function (...args: any) {
      ERROR(fileName, ...args);
    }
  };
}
